`
You should see the following output:
$ chmod u+x basic_while.sh
$ ./basic_while.sh
Looping...
Looping...
--snip--
Next, let’s write a more sophisticated while loop that runs until it finds a
specific file on the filesystem (use CTRL+C to stop it from executing at any
point):
#!/bin/bash
1 SIGNAL_TO_STOP_FILE="stoploop"
2 while [[ ! -f "${SIGNAL_TO_STOP_FILE}" ]]; do
echo "The file ${SIGNAL_TO_STOP_FILE} does not yet exist..."
echo "Checking again in 2 seconds..."
sleep 2
done
3 echo "File was found! exiting..."
At 1, we define a variable representing the name of the file for which the
while loop 2 checks using a file test operator. The loop won’t exit until the
condition is satisfied. Once the file is available, the loop will stop, and the script
will continue to the echo command 3. Save this file as while_loop.sh and run it:
$ chmod u+x while_loop.sh
$./while_loop.sh
The file stoploop does not yet exist...
Checking again in 2 seconds...
--snip--
While the script is running, open a second terminal in the same directory as
the script and create the stoploop file:
$ touch stoploop
Once you’ve done so, you should see the script breaking out of the loop and
print the following:
File was found! exiting...
This script is available at https://github.com/dolevf/Black-Hat-
Bash/blob/master/ch02/while_loop.sh.
until
Although while runs so long as the condition succeeds, until runs so long
as it fails. Listing 2-11 shows the until loop syntax.
until some_condition; do
Black Hat Bash (Early Access) © 2023 by Dolev Farhi and Nick Aleks